<template>
  <view class="user-container">
    <navbar title="个人中心"></navbar>

    <view class="group">
      <view class="row-container" @click="tryUpdateAvatar">
        <text class="label">头像</text>
        <image :src="mine.avatarUrl" v-if="mine&&mine.avatarUrl" mode="aspectFill" class="avatar"></image>
        <image src="../../static/weidenglu@3x.png" v-else class="avatar"></image>
        <image src="../../static/black_back.png" class="arrow"></image>
      </view>
      <view class="divider"></view>
      <view class="row-container" @click="toUsername">
        <text class="label">用户名</text>
        <text class="sub-label">{{ mine.name }}</text>
        <image src="../../static/black_back.png" class="arrow"></image>
      </view>
    </view>
  </view>
</template>

<script>
import {
  mapActions,
  mapGetters
} from 'vuex'
import {
  commonApi
} from '@/api.js'
import navbar from '@/components/navbar'
import permissionUtils from "@/libs/permissionUtils";

export default {
  components: {
    navbar
  },
  data() {
    return {}
  },
  computed: {
    ...mapGetters(['mine'])
  },
  methods: {
    ...mapActions(['logout', 'refreshUser']),

    toBack() {
      uni.navigateBack()
    },

    tryUpdateAvatar() {
      this.chooseImage()
    },
    async chooseImage() {
      const res = await permissionUtils.request('album', {
        title: '存储权限',
        desc: '当您使用APP时，会在上传头像时访问存储权限。不授权上述权限，不影响APP其它功能使用。'
      })

      if (res.status !== 1) {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
        return
      }

      uni.chooseImage({
        count: 1,
        sourceType: ['album'],
        sizeType: 'compressed',
        success: async (result) => {
          const filePath = result.tempFilePaths[0];

          uni.showLoading()
          const res = await commonApi.getUploadToken()
          const {
            token,
            imgHost,
            url
          } = res.data.data

          var key = Math.random().toString(36).substr(2); //生成一个随机字符串的文件名

          uni.uploadFile({
            url, //华东地区上传地址
            filePath,
            name: 'file',
            formData: {
              token, //刚刚获取的上传凭证
              'key': 'avatar/' + key //这里是为文件设置上传后的文件名
            },
            success: async (uploadFileRes) => {
              console.log(uploadFileRes.data)
              const data = JSON.parse(uploadFileRes.data.trim())
              const avatar = imgHost + '/' + data.key

              await commonApi.updateAvatar(avatar)
              await this.refreshUser()
            },
            fail: (e) => {
              console.log('hsf', 'uploadFile===error:' + JSON.stringify(e));
            },

            complete() {
              uni.hideLoading()
            }
          })


          uni.hideLoading()
        }
      })
    },

    toUsername() {
      uni.navigateTo({
        url: '/pages/username/username',
      });
    }
  }
}
</script>
<style lang="scss">
page {
  background-color: #f8f8f8;
}

.user-container {
  display: flex;
  flex-direction: column;
}
</style>
